package com.sailing.websocket.common;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * @作者:邹蕴果
 * @创建时间：2021/7/19
 * @修改时间：2021/7/21
 */

@Component
@ServerEndpoint(value = "/socket/{name}")
public class WebSocketServer {


    //当前在线连接数
    private static AtomicInteger online = new AtomicInteger();

    //存放每个客户端对应的WebSocketServer对象
    private static ConcurrentHashMap<String,Session> sessionPools = new ConcurrentHashMap<String,Session>();

   //给WebSocket对象发送消息
    public void sendMessage(Session session, String message) throws IOException{
        if(session != null){
            session.getBasicRemote().sendText(message);
        }
    }


    //连接建立成功触发函数
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "name") String userName){
        sessionPools.put(userName, session);
        addOnlineCount();
        System.out.println(userName + "加入webSocket！当前人数为" + online);

    }

    //连接关闭触发函数
    @OnClose
    public void onClose(@PathParam(value = "name") String userName){
        sessionPools.remove(userName);
        subOnlineCount();
        System.out.println(userName + "断开webSocket连接！当前人数为" + online);
    }

    //服务器收到消息时触发函数
    @OnMessage
    public void onMessage(String message) throws IOException{
        //将消息分为消息体/发送者/接收者
        String sendMessage = message.split("[|]")[0];
        String sendUserno = message.split("[|]")[2];
        String senderno =message.split("[|]")[1];
        System.out.println(message);
        if(sessionPools.get(sendUserno)!=null){
         Session sessionSpecified= sessionPools.get(sendUserno);
        //如对方在线，发给对方
         try{
             sendMessage(sessionSpecified,sendMessage+"|"+senderno);
           /*  sendMessage(sessionSender,"Sender:"+senderno+"/n"+sendMessage);*/
         }catch (Exception e){
             e.printStackTrace();
         }
        }
        else{
            Session sessionSender = sessionPools.get(senderno);
            try{
                sendMessage(sessionSender,"对方不在线|error");
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    //发生错误时触发函数
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }



    public static void addOnlineCount(){
        online.incrementAndGet();
    }

    public static void subOnlineCount() {
        online.decrementAndGet();
    }
}
